package com.youlu.campus.service.data.impl;

import com.alibaba.fastjson.JSON;
import com.youlu.campus.entity.ActivityInfo;
import com.youlu.campus.entity.ActivityQaInfo;
import com.youlu.campus.entity.VO.req.UvPvVO;
import com.youlu.campus.service.cache.CacheActivityService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class UvPvService {

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private CacheActivityService cacheActivityService;

    @Value("${mq.topic.pv-uv}")
    private String topic;

    @Value("${mq.topic.activityInfo}")
    private String activityTopic;

    /**
     * 统计页面uv pv
     *
     * @param uvPv
     */
    public void doUvPv(UvPvVO uvPv) {
        ActivityInfo activityInfo = cacheActivityService.findById(uvPv.getActivityId());
        uvPv.setActivityName(activityInfo.getName());
        log.info("doUvPv 处理客户端 ->{},type:{},activityId:{}", uvPv.getClientIp(), uvPv.getType(), uvPv.getActivityId());
        rocketMQTemplate.asyncSend(topic + ":TAG", JSON.toJSONString(uvPv), new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
            }

            @Override
            public void onException(Throwable throwable) {
                log.error("PV UV 处理客户端 ->{} 消息失败", uvPv.getClientIp(), throwable);
            }
        });
    }

    public void doActivityInfo(ActivityQaInfo activityQaInfo) {
        rocketMQTemplate.asyncSend(activityTopic + ":TAG", JSON.toJSONString(activityQaInfo), new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
            }

            @Override
            public void onException(Throwable throwable) {
                log.error("活动 ->{} 同步是失败 消息失败", activityQaInfo.getActivityName(), throwable);
            }
        });
    }
}
